define(["angularAMD"], function (angularAMD) {
    angularAMD.service('B0202Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', "$timeout", "$mddProvider",
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $timeout, $mddProvider) {
            this.init = function (options, feedback) {
                //var machine_no;
                var machineList = options.machineList;
                var type = options.type;
                var tmpOnWorkInfo = {}; // 查人員資訊
                var preOnWorkInfo = {}; // 前次上工
                var need_work_reason = (config.cache.sys_parameter.EmployeeWorkReason == '1' || config.cache.sys_parameter.EmployeeWorkReason == '3'); //上工是否需輸入原因
                let need_check = false;// 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                let check_member = ''; 
                function beforeEmpWorkSet(dialog, callback) {
                    if (need_work_reason && !dialog.tmpOnWorkInfo.reason_no) {
                        loadEmpWorkReason('', function (selectItem) {
                            dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                            dialog.tmpOnWorkInfo.reason_name_display = selectItem.page_name;
                            if (callback)
                                callback();
                        });
                    } else {
                        if (callback)
                            callback();
                    }
                }

                // 人員原因基本資料取得
                function loadEmpWorkReason(reason_no, callback) {
                    $MMWService.pageNumberInfoGet({
                        // page_mode: '35',
                        form_name: 'PageNo_27',
                        query_condition_info: [
                            { column_name: 'REASONTYPE', query_mode: '0', value: '0', merge_condition_model: 'AND' },
                            { column_name: 'ISSUESTATE', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                        ]
                    }, function (items) {
                        if (items && items.length > 0) {
                            $rootScope.showSelect({
                                label: function (item) {
                                    return item.page_name + '(' + item.page_no + ')';
                                },
                                title: $filter('translate')('B0202.plz_select_reason'),
                                code: 'page_no',
                                selectCode: reason_no || '',
                                list: items,
                                confirm: function (selectItem, radio_dialog) {
                                    radio_dialog.hide();
                                    if (callback)
                                        callback(selectItem);
                                }
                            });
                        } else {
                            $rootScope.showAlert($filter('translate')('B0202.showAlert.column6'));
                        }
                    });
                }

                function addWorkItem(tmpOnWorkInfo, machine, employeewrokset) {
                    var msg = '';
                    if (type == 'machine') {
                        //machineList.forEach(function(machine_detail){
                        for (var i = 0; i < machine.employee_work_detail.length; i++) {
                            if (tmpOnWorkInfo.employee_no == machine.employee_work_detail[i].employee_no) {
                                msg += $filter('translate')('B0202.msg.column1') + machine.machine_no + $filter('translate')('B0202.msg.column2') + tmpOnWorkInfo.employee_no + $filter('translate')('B0202.msg.column3') + "<br>";
                                break;
                            }
                        }
                        //});
                    }
                    if (need_work_reason && !tmpOnWorkInfo.reason_no) {
                        msg += $filter('translate')('B0202.showAlert.column5') + "<br>";
                    }
                    if (msg == '') {
                        employeewrokset.push({
                            machine_no: machine.machine_no,
                            machine_name: machine.machine_name,
                            employee_no: tmpOnWorkInfo.employee_no,
                            work_mode: 'U',
                            work_datetime: new Date(),
                            reason_no: tmpOnWorkInfo.reason_no || ''
                        });
                    }
                    return msg;
                }

                //上工
                function empWorkSet(dialog) {
                    var msg = '';
                    var content = {
                        employeewrokset:[]
                    
                   };
                    machineList.forEach(function (machine) {
                        msg += addWorkItem(dialog.tmpOnWorkInfo, machine, content.employeewrokset);
                    });
                    //console.log(content.employeewrokset);
                    //M#84747
                    if (content.employeewrokset.length > 0)
                        employee_wrok_set_Imp(dialog, content);
                    else
                        $rootScope.showAlert(msg);
                    /*if(msg == ''){
                        employee_wrok_set_Imp(dialog, content);
                    } else {
                        $rootScope.showAlert(msg);
                    }*/
                }

                // 人員技能檢驗
                function inspectUserSkill(inspectInfo, feedback) {
                    if (inspectInfo.employeewrokset && inspectInfo.employeewrokset.length > 0) {
                        var machineInfo = inspectInfo.employeewrokset.shift();
                        if (machineInfo.work_mode == 'U' && inspectInfo.parent != 'B0201') { //生產線作業平台不支援技能檢驗
                            $mdDialog.serviceDialog('B0231Service', {
                                parent: inspectInfo.parent,
                                machine_no: machineInfo.machine_no,
                                machine_name: machineInfo.machine_name,
                                position_no: machineInfo.position,
                                op_no: inspectInfo.op_no,
                                area_no: inspectInfo.area_no,
                                user_no: inspectInfo.user_no,
                                user_name: inspectInfo.user_name,
                                user_title: inspectInfo.user_title,
                                releaser_verified: inspectInfo.releaser_verified,
                                feedback: function (dialog) {
                                    if (dialog) {
                                        inspectInfo.releaser_verified = dialog.releaser_verified;
                                        dialog.hide();
                                    }
                                    inspectUserSkill(inspectInfo, feedback);
                                },
                                req_check:function(info){ // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                                    need_check = true;
                                    check_member = info.account;
                                 }
                            });
                        } else {
                            if (feedback)
                                feedback();
                        }
                    } else {
                        if (feedback)
                            feedback();
                    }
                }

                function employee_wrok_set_Imp(dialog, content) {
                    var inspectInfo = {
                        parent: options.parent,
                        op_no: '',
                        area_no: '',
                        user_no: dialog.tmpOnWorkInfo.employee_no,
                        user_name: dialog.tmpOnWorkInfo.employee_name,
                        user_title: dialog.tmpOnWorkInfo.user_title,
                        releaser_verified: false,
                        employeewrokset: angular.extend([], content.employeewrokset)
                    };
                    inspectUserSkill(inspectInfo, function () {
                        employee_wrok_set(dialog, content);
                    });
                }

                function employee_wrok_set(dialog, content) {
                    //20180518 modify by 李栋 for mantis#0047068
                    if(need_check){ // 20231218 add by shiwl for M#0151498: 力邦合信，正式区。人员技能检核以后无记录写入数据库
                        content.employeewrokset[0].need_check_skill = '1';
                        content.employeewrokset[0].skill_check_result = '0'
                        content.employeewrokset[0].skill_pass_user = check_member;
                   } else {
                       content.employeewrokset[0].need_check_skill = '0';
                       content.employeewrokset[0].skill_check_result = '1'
                       content.employeewrokset[0].skill_pass_user = '';
                   }
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                        content: content,
                        success: function (data) {
                            $rootScope.showToast($filter('translate')('B0202.showAlert.column1'));
                            //更新歷史下工紀錄
                            dialog.preOnWorkInfo.employee_no = dialog.tmpOnWorkInfo.employee_no;
                            dialog.preOnWorkInfo.employee_name = dialog.tmpOnWorkInfo.employee_name;
                            dialog.preOnWorkInfo.work_time = dialog.tmpOnWorkInfo.shift_start_time;
                            dialog.tmpOnWorkInfo = {};
                            dialog.tmpEmp_no = '';
                            try {
                                document.getElementById('tmpEmp_no').focus();
                                if (dialog.ic_card != '') {//允许连续刷IC卡上工
                                    dialog.ic_card = '';
                                    document.getElementById('ic_card').focus();
                                }
                            } catch (e) { console.error(e); }
                            if (feedback)
                                feedback();
                        }
                    });
                }
                $mddProvider.UseForm ('B0202Service', () => {
                    $mdDialog.dialog(
                    'module/moduleB/program/B02/B0202/B0202.html',
                    function (dialog) {
                        return {
                            css_url: 'JSplugins/angular-material-lite/template/dynamicService.tmp.css',
                            machine_list: machineList,
                            machine_no: machineList[0].machine_no,  //設備
                            tmpEmp_no: '',
                            tmpOnWorkInfo: tmpOnWorkInfo,
                            preOnWorkInfo: preOnWorkInfo,
                            need_work_reason: need_work_reason,
                            parent: options.parent,
                            ic_card: '',  //IC卡
                            _event: {
                                'tmpEmp_no':{
                                    click: (value, event) => {
                                        dialog.searchEmp()
                                    },
                                    change: (tmpEmp_no, event) => {
                                        dialog.searchEmp(event)
                                    }
                                },
                                'ic_card': {
                                    click: (ic_card, event) => {
                                        dialog.ICCardScanner()
                                    },
                                    change: (ic_card, event) => {
                                        dialog.searchICCard(event)
                                    }
                                },
                                'tmpOnWorkInfo.reason_name': {
                                    click: () => {
                                        loadEmpWorkReason('', function (selectItem) {
                                            dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                                            dialog.tmpOnWorkInfo.reason_name_display = selectItem.page_name;
                                            empWorkSet(dialog);
                                        });
                                    }
                                }
                            },
                            _fn:{
                                'confirm': {
                                    click: (value,column1,event) => {
                                        dialog.searchEmp()
                                    }
                                }
                            },
                            ICCardScanner: function () {//20200723 add by linzh for M#71988
                                $rootScope.OpenScanner({
                                    after: function (result) {
                                        $timeout(function () {
                                            dialog.ic_card = result.text;
                                            dialog.searchICCard();
                                        });
                                    },
                                    exception: function () {
                                        //目前裝置無法使用相機
                                        $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                    },
                                    orientation: 'landscape'
                                });
                            },
                            searchICCard: function (event) {//20200710 add by linzh for M#71988
                                if (!event || event.event.keyCode == 13) {
                                    if (dialog.ic_card != '') {
                                        var content = {
                                            IcNo: dialog.ic_card
                                        }
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_SYS.ic_card_info_get',
                                            content: content,
                                            success: function (data) {
                                                if (data.UserNo != null && data.PassWord != null) {
                                                    dialog.tmpEmp_no = data.UserNo;
                                                    dialog.searchEmp();//调用员工信息查询方法
                                                }
                                                else {
                                                    $rootScope.showAlert($filter('translate')('Login.error.ic_card_error'));
                                                    dialog.ic_card = '';
                                                    document.getElementById('ic_card').focus();
                                                }
                                            },
                                            error: function (data) {
                                                $rootScope.showAlert(data.Message);
                                                dialog.ic_card = '';
                                                document.getElementById('ic_card').focus();
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0202.showAlert.column7'));
                                        dialog.ic_card = '';
                                        document.getElementById('ic_card').focus();
                                    }
                                }
                            },
                            beforeShown: function () {
                                try {
                                    // 20231102 modify by shiwl 0149220: 贝士达：6.0 MES系统测试区，开启扫描模式后，登录界面还有上工界面光标标未定位到IC卡栏位                                                        
                                    $timeout(function(){
                                        if(config.setting.scanBarcod == "Y"){
                                            document.getElementById('ic_card').focus();
                                        } else {
                                            document.getElementById('tmpEmp_no').focus();
                                        }
                                    },1000);
                                } catch (e) { console.error(e); }
                            },
                            searchEmp: function (event, feedback) {
                                if (!event || event.event.keyCode == 13) {
                                    if (dialog.tmpEmp_no != '') {
                                        //20190705 modify by Dustdusk for M#59580: 將員工編號自動大寫
                                        dialog.tmpEmp_no = dialog.tmpEmp_no.toUpperCase();
                                        var content = {
                                            machine_no: dialog.machine_no,
                                            employee_no: dialog.tmpEmp_no,
                                            report_datetime: new Date(),
                                            //return_type : '0'
                                            return_type: '10'
                                        };

                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_SYS.user_information_get',
                                            content: content,
                                            success: function (data) {
                                                dialog.tmpOnWorkInfo = data;
                                                dialog.tmpOnWorkInfo.shift_start_time = new Date();
                                                if (config.setting.autoWorkset)
                                                    dialog.confirm();
                                            },
                                            error: function (data) {
                                                $rootScope.showAlert(data.Message);
                                                document.getElementById('tmpEmp_no').focus();
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0202.showAlert.column2'));
                                        document.getElementById('tmpEmp_no').focus();
                                    }
                                }
                            },
                            loadEmpWorkReason: function () {
                                loadEmpWorkReason(dialog.tmpOnWorkInfo.reason_no, function (selectItem) {
                                    dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                                    dialog.tmpOnWorkInfo.reason_name = selectItem.page_name;
                                });
                            },
                            back: function () {
                                this.hide();
                            },
                            confirm: function () {
                                var isOnWork = false;
                                if (dialog.tmpEmp_no != '') { //檢核是否有輸入上工人員
                                    if (!dialog.tmpOnWorkInfo.employee_work_detail) {
                                        $rootScope.showAlert($filter('translate')('B0202.showAlert.column3'));
                                        document.getElementById('tmpEmp_no').focus();
                                    } else {
                                        //20170602 modify by Dustdusk for 作業區也需要檢核是否上工過
                                        //if(type=='line'){
                                        //為生產線
                                        var msg = '';
                                        var confirm;
                                        if (dialog.tmpOnWorkInfo.employee_work_detail.length != 0) {
                                            for (var i = 0; i < dialog.tmpOnWorkInfo.employee_work_detail.length; i++) {
                                                if (dialog.machine_no == dialog.tmpOnWorkInfo.employee_work_detail[i].machine_no) {
                                                    msg = $filter('translate')('B0202.showAlert.column4');
                                                    confirm = function () {
                                                        dialog.tmpOnWorkInfo = {};
                                                        dialog.tmpEmp_no = '';
                                                        if (dialog.ic_card != '') {//允许连续刷IC卡下工
                                                            dialog.ic_card = '';
                                                            document.getElementById('ic_card').focus();
                                                        } else {
                                                            document.getElementById('tmpEmp_no').focus();
                                                        }
                                                    };
                                                    break;
                                                }
                                            }
                                        }
                                        //M#84747 上下工訊息不卡控
                                        beforeEmpWorkSet(dialog, function () {
                                            empWorkSet(dialog);
                                        });
                                        /*if(msg == ''){
                                            beforeEmpWorkSet(dialog, function(){
                                                empWorkSet(dialog);
                                            });
                                        } else {
                                            $rootScope.showAlert(msg, confirm);
                                        }*/

                                        // } else {
                                        //     //為作業區
                                        //     empWorkSet(dialog);
                                        // }
                                    }
                                } else {
                                    $rootScope.showAlert($filter('translate')('B0202.showAlert.column2'));
                                    document.getElementById('tmpEmp_no').focus();
                                }
                            }
                        };
                    }
                );})
            };
        }]);
});
